package com.example.service.webhook.business.bank.service;

import com.example.service.webhook.business.bank.api.BankClient;
import com.example.service.webhook.business.bank.billitem.BankBillTask;
import com.example.service.webhook.business.bank.dtonew.*;
import com.example.service.webhook.business.bank.entity.*;
import com.example.service.webhook.business.bank.repository.*;
import com.example.service.webhook.util.DateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;

/**
 * 邮箱账单处理类 1、账单 2、消费记录 3、分期记录 ClassName: BillService date: 2016年7月20日 下午5:35:35
 * 
 * @author yuandong
 * @version
 * @since JDK 1.6
 */
@Service
public class BankBillService {
	private static final Logger LOGGER = LoggerFactory.getLogger(BankBillService.class);

	@Autowired
	private BankClient bankClient;

	@Autowired
	private BankCardRepository bankCardRepository;

	@Autowired
	private BankBillRepository bankBillRepository;

	@Autowired
	private BankBillShoppingSheetRepository bankBillShoppingSheetRepository;
	
	@Autowired
	private BankBillDepositRepository bankBillDepositRepository;
	@Autowired
	private BankBillInstallmentRepository bankBillInstallmentRepository;

	@Autowired
	private ThreadPoolTaskExecutor taskExecutor;

	/**
	 * 
	 * fetchBill:处理邮箱下面的所有账单 <br/>
	 * 在收到魔蝎的邮箱账单回调时执行<br/>
	 * for(保存账单){ 保存单条账单 －保存消费记录 －保存分期记录 }<br/>
	 * 
	 * @author yuandong
	 * @param task
	 * @since JDK 1.6
	 */
	public void fetchBill(final BankBillTask task) {
		// 这里交给线程池处理，防止下面的业务处理时间太长，导致超时。
		// 超时会导致魔蝎数据进行重试，会收到重复的回调请求

		taskExecutor.execute(new Runnable() {
			@Override
			public void run() {
				try {
					String taskId = task.getTaskId();
					LOGGER.info(taskId);
					List<CardDetail> cardDetailsList = bankClient.getCardsByTaskId(taskId);
					if(cardDetailsList!=null&&cardDetailsList.size()>0){
						LOGGER.info("cardDetailsList size :"+cardDetailsList.size());
						for(CardDetail cardDetail: cardDetailsList){
							BankCardEntity bankCardEntity = new BankCardEntity();
							BeanUtils.copyProperties(cardDetail, bankCardEntity);
							bankCardEntity.setUserId(task.getUserId());
							BankCardEntity isexistCard = bankCardRepository.getBankCard(task.getUserId(),
									bankCardEntity.getCardId());
							if (isexistCard != null) {
								bankCardEntity.setId(isexistCard.getId());
								bankCardEntity.setCreateTime(isexistCard.getCreateTime());
								bankCardRepository.updateBankCard(bankCardEntity);
							} else {
								bankCardRepository.saveBankCard(bankCardEntity);
							}
							if(cardDetail.getBills()!=null&&!cardDetail.getBills().isEmpty()){
								for(BillDetail billDetail:cardDetail.getBills()){
									BankBillEntity bankBillEntity = new BankBillEntity();
									BeanUtils.copyProperties(billDetail, bankBillEntity);
									bankBillEntity.setCardId(cardDetail.getCardId());
									bankBillEntity.setCardType(cardDetail.getCardType());
									bankBillEntity.setUserId(task.getUserId());
									bankBillEntity.setCardNums(cardDetail.getCardNo());
									bankBillEntity.setFullCardNums(cardDetail.getFullCardNo());
									bankBillEntity.setNameOnCard(cardDetail.getNameOnCard());
									
								    //银行卡账单
									BankBillEntity isexistBill = bankBillRepository.getTBillByBillMonth(
											bankBillEntity.getUserId(), bankBillEntity.getCardId(),
											bankBillEntity.getBillMonth());

									if (isexistBill != null) {
										bankBillEntity.setId(isexistBill.getId());
										bankBillEntity.setCreateTime(isexistBill.getCreateTime());
										bankBillRepository.updateBill(bankBillEntity);
									} else {
										bankBillEntity.setCreateTime(DateUtil.getCurrentDate());
										bankBillEntity.setLastModifyTime(DateUtil.getCurrentDate());
										bankBillRepository.saveAndReturnKey(bankBillEntity);
									}
									
									
									//消费记录
									if(billDetail.getItems()!=null&&!billDetail.getItems().isEmpty()){
										bankBillShoppingSheetRepository.deleteShoppingSheetByBillId(bankBillEntity.getBillId(), task.getUserId());
										for(BillItem billItem:billDetail.getItems()){
											BankBillShoppingSheetEntity billItemEntity = new BankBillShoppingSheetEntity();
											BeanUtils.copyProperties(billItem, billItemEntity);
											billItemEntity.setShoppingsheetId(billItem.getId());
											billItemEntity.setUserId(task.getUserId());
											billItemEntity.setBankName(bankBillEntity.getBankName());
											billItemEntity.setBillMonth(bankBillEntity.getBillMonth());
											billItemEntity.setBillId(bankBillEntity.getBillId());
											bankBillShoppingSheetRepository.saveBillShoppingSheet(billItemEntity, task.getUserId());
										}
									}
									//分期记录
									if(billDetail.getInstallments()!=null&&!billDetail.getInstallments().isEmpty()){
										bankBillInstallmentRepository.deleteBillInstallmentByBillId(bankBillEntity.getBillId(), task.getUserId());
										for(Installment installment:billDetail.getInstallments()){
											BankBillInstallmentEntity installmentEntity = new BankBillInstallmentEntity();
											BeanUtils.copyProperties(installment, installmentEntity);
											installmentEntity.setCardId(cardDetail.getCardId());
											installmentEntity.setBillId(bankBillEntity.getBillId());
											bankBillInstallmentRepository.saveBillInstallment(installmentEntity, task.getUserId());
										}
									}
								}
							}
							
							//借记卡定期数据
							if(cardDetail.getDeposits()!=null&&!cardDetail.getDeposits().isEmpty()){
								bankBillDepositRepository.deleteBankBillDepositByBillId(cardDetail.getCardId(), task.getUserId());
								for(CardDeposit cardDeposit:cardDetail.getDeposits()){
									BankBillDepositEntity bankBillDepositEntity = new BankBillDepositEntity();
									BeanUtils.copyProperties(cardDeposit, bankBillDepositEntity);
									bankBillDepositEntity.setUserId(task.getUserId());
									bankBillDepositEntity.setCardId(cardDetail.getCardId());
									bankBillDepositRepository.saveBankBillDeposit(bankBillDepositEntity, task.getUserId());
								}
							}
							
							
							
				
						}
					}
					
					
					
					
					
//					List<BankCard> cards = task.getCards();
//
//					if (cards != null && !cards.isEmpty()) {
//						for (BankCard bankCard : cards) {
//							BankCardEntity bankCardEntity = loadBankCardByCallApi(bankCard.getCardId());
//							bankCardEntity.setUserId(task.getUserId());
//							// 判断卡是否存在，存在则更新。额度信息银行可能会调整，所以要更新
//							// 目前我建的t_card表里面 userid＋cardid是唯一约束
//							// 这里要根据自己的业务来调整。如果不关心userid，可以以cardid做主键
//							BankCardEntity isexistCard = bankCardRepository.getBankCard(task.getUserId(),
//									bankCard.getCardId());
//							if (isexistCard != null) {
//								bankCardEntity.setId(isexistCard.getId());
//								bankCardEntity.setCreateTime(isexistCard.getCreateTime());
//								bankCardRepository.updateBankCard(bankCardEntity);
//							} else {
//
//								bankCardRepository.saveBankCard(bankCardEntity);
//							}
//							if (bankCard.getBills() != null && !bankCard.getBills().isEmpty()) {
//								for (BankBillItem billItem : bankCard.getBills()) {
//									// 新增账单
//									BankBillEntity bankBillEntity = loadBankBillByCallApi(task.getUserId(),
//											bankCard.getCardId(), billItem.getBillId());
//									// 以userId+cardId+billId作为bill的唯一约束。这里要根据自己的业务来调整。
//									// 在不以卡为中心的业务中，可以以userId+billId作为唯一约束
//									BankBillEntity isexistBill = bankBillRepository.getTBillById(
//											bankBillEntity.getUserId(), bankBillEntity.getCardId(),
//											bankBillEntity.getBillId());
//
//									if (isexistBill != null) {
//										bankBillEntity.setId(isexistBill.getId());
//										bankBillEntity.setCreateTime(isexistBill.getCreateTime());
//										bankBillRepository.updateBill(bankBillEntity);
//									} else {
//										bankBillRepository.saveBill(bankBillEntity);
//									}
//
//									// 处理消费记录：消费记录只关联bill，不去关联card
//									// 查询消费记录
//									List<BankBillShoppingSheetEntity> billItemEntities = loadBillShoppingSheetByCallApi(
//											bankBillEntity.getBillId());
//									// 保存消费记录
//									saveBillShoppingSheet(bankBillEntity, billItemEntities, task.getUserId());
//
//								}
//							}
//
//						}
//
//					}
				} catch (Exception e) {
					LOGGER.error("fetchBill failed. task:{}", task.getTaskId(), e);
				}
			}
		}

		);
	}

	/*private BankCardEntity loadBankCardByCallApi(String cardId) throws IOException {
		BankCardInfo bankCardInfo = bankClient.getCardInfoByCardId(cardId);
		if (bankCardInfo != null) {
			BankCardEntity bankCardEntity = new BankCardEntity();
			BeanUtils.copyProperties(bankCardInfo, bankCardEntity);
			bankCardEntity.setCardId(cardId);
			return bankCardEntity;
		}
		return null;
	}

	private BankBillEntity loadBankBillByCallApi(String userId, String cardId, String billId) throws IOException {
		BankBill bankBill = bankClient.getBillById(billId);
		if (bankBill != null) {
			BankBillEntity bankBillEntity = new BankBillEntity();
			BeanUtils.copyProperties(bankBill, bankBillEntity);
			bankBillEntity.setCardId(cardId);
			bankBillEntity.setUserId(userId);
			return bankBillEntity;
		}
		return null;
	}*/

	/**
	 * 消费记录是分页查询。 loadBillItemsByCallApi:分页查询消费记录 <br/>
	 * size在魔蝎那边默认是2000，page默认1.<br/>
	 * 
	 * @author yuandong
	 * @param billId
	 * @return
	 * @throws IOException
	 * @since JDK 1.6
	 */
	/*private List<BankBillShoppingSheetEntity> loadBillShoppingSheetByCallApi(String billId) throws IOException {
		List<BankBillShoppingSheetEntity> billItemEntities = Lists.newArrayList();
		int size = 200;
		int page = 1;

		do {
			BankBillShoppingSheetList creditBillItems = bankClient.getBillShoppingSheets(billId, page, size);
			if (creditBillItems != null && creditBillItems.getSize() > 0) {
				size = creditBillItems.getSize();
				LOGGER.info("loadBillShoppingSheetByCallApi success. billId:{}", billId);
				List<BankBillShoppingSheet> shoppingSheets = creditBillItems.getShoppingSheets();
				for (BankBillShoppingSheet shoppingSheet : shoppingSheets) {
					BankBillShoppingSheetEntity billItemEntity = new BankBillShoppingSheetEntity();
					BeanUtils.copyProperties(shoppingSheet, billItemEntity);
					billItemEntities.add(billItemEntity);
				}
			} else {
				size = 0;
			}
			page++;
		} while (size == 200);

		return billItemEntities;
	}*/

//	// 保存消费记录
//	private void saveBillShoppingSheet(BankBillEntity billEntity, List<BankBillShoppingSheetEntity> billItemEntities,
//			String userId) throws Exception {
//		if (billItemEntities != null && !billItemEntities.isEmpty()) {
//
//			// 先执行一次删除，防止已经有消费记录了
//			bankBillShoppingSheetRepository.deleteShoppingSheetByBillId(billEntity.getBillId(), userId);
//
//			for (BankBillShoppingSheetEntity bankBillShoppingSheetEntity : billItemEntities) {
//				// billId和userId也放在消费记录里面，方便以后查询用
//				bankBillShoppingSheetEntity.setBillId(billEntity.getBillId());
//				bankBillShoppingSheetEntity.setUserId(billEntity.getUserId());
//				// 保存
//				bankBillShoppingSheetRepository.saveBillShoppingSheet(bankBillShoppingSheetEntity, userId);
//			}
//		}
//	}

}
